package com.javaketang.dky.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.javaketang.dky.entity.*;
import com.javaketang.dky.mapper.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpSession;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author dky
 * @since 2021-07-13
 */
@Controller
@RequestMapping("car")
public class ShoppingCarController {

    //商品类
    @Resource
    private EasybuyProductMapper productMapper;

    //购物车类
    @Resource
    private ShoppingCarMapper carMapper;

    //商品详情类
    @Resource
    private EasybuyProductCategoryMapper categoryMapper;

    //新闻类
    @Resource
    private EasybuyNewsMapper newsMapper;

    //地址类
    @Resource
    private EasybuyUserAddressMapper addressMapper;

    /**
     * 加入购物车方法
     *
     * @param id 商品id
     * @return
     */
    @RequestMapping("/joinShopping")
    @ResponseBody
    public Map<String, Object> joinShopping(Integer id, Integer number, HttpSession session, Model model) {

        //创建map集合
        Map<String, Object> map = new HashMap<>();

        //获取session
        EasybuyUser user = (EasybuyUser) session.getAttribute("userSession");

        //根据id查询商品
        EasybuyProduct product = productMapper.selectById(id);

        //查询购物车
        List<ShoppingCar> productId = carMapper.selectList(new QueryWrapper<ShoppingCar>().eq("productId", id).eq("isDelete", 0).eq("userId", user.getId()));


        //判断如果商品id相等时说明已存在，直接加数量
        if (productId.size() > 0) {


            //购物车对象
            ShoppingCar car = new ShoppingCar();

            //查询购物车
            List<ShoppingCar> productId1 = carMapper.selectList(new QueryWrapper<ShoppingCar>().eq("productId", id));

            car.setId(productId.get(0).getId());  //赋值id
            car.setNumber(productId.get(0).getNumber() + number);  //赋值数量
            double sumPrice = car.getNumber() * product.getPrice(); //计算总金额
            car.setSumPrice(sumPrice);  //赋值总金额


            //判断库存
            if (number <= product.getStock()) {

                //商品类
                EasybuyProduct easybuyProduct = new EasybuyProduct();
                easybuyProduct.setId(id); //商品id
                Integer stock = product.getStock() - number;
                easybuyProduct.setStock(stock); //库存

                int updateByIdProduct = productMapper.updateById(easybuyProduct);

                //判断修改库存成功
                if (updateByIdProduct > 0) {

                    int row = carMapper.updateById(car);  //修改方法

                    //判断修改成功时
                    if (row > 0) {

                        map.put("status", 1);
                        map.put("message", "添加成功！");

                        //根据id查询商品
                        EasybuyProduct product1 = productMapper.selectById(id);

                        //查询购物车
                        List<ShoppingCar> order = carMapper.selectList(new QueryWrapper<ShoppingCar>().eq("userId", user == null ? 0 : user.getId()).eq("isDelete", 0));    //查询订单

                        map.put("order", order);
                        map.put("product", product1);
                    } else {
                        map.put("status", 0);
                        map.put("message", "添加失败！");
                    }

                } else {
                    map.put("status", 0);
                    map.put("message", "修改库存失败！");
                }


            } else {
                map.put("status", 0);
                map.put("message", "库存数量不足！");
            }

            //判断是第一次添加购物车时
        } else {

            //购物车对象
            ShoppingCar car = new ShoppingCar();

            car.setUserId(user.getId());//赋值用户id
            car.setName(product.getName());  //赋值商品名称
            car.setPrice(product.getPrice());//赋值价格
            car.setImages(product.getFileName());//赋值图片
            car.setNumber(number);//数量为1
            double sumPrice = car.getNumber() * car.getPrice(); //计算总金额
            car.setSumPrice(sumPrice);  //赋值总金额
            car.setProductId(product.getId());


            //商品类
            EasybuyProduct easybuyProduct = new EasybuyProduct();
            easybuyProduct.setId(id); //商品id
            Integer stock = product.getStock() - number;
            easybuyProduct.setStock(stock); //库存


            //判断库存
            if (car.getNumber() <= product.getStock()) {

                int row = carMapper.insert(car);//添加方法

                int updateByIdProduct = productMapper.updateById(easybuyProduct);

                //判断修改库存成功
                if (updateByIdProduct > 0) {

                    //判断修改成功时
                    if (row > 0) {
                        map.put("status", 1);
                        map.put("message", "添加成功！");

                        //根据id查询商品
                        EasybuyProduct product1 = productMapper.selectById(id);

                        //查询购物车
                        List<ShoppingCar> order = carMapper.selectList(new QueryWrapper<ShoppingCar>().eq("userId", user == null ? 0 : user.getId()).eq("isDelete", 0));    //查询订单

                        map.put("order", order);
                        map.put("product", product1);
                    } else {
                        map.put("status", 0);
                        map.put("message", "添加失败！");
                    }

                } else {
                    map.put("status", 0);
                    map.put("message", "修改库存失败！");
                }

            } else {
                map.put("status", 0);
                map.put("message", "库存数量不足！");
            }

        }

        return map;
    }

    /**
     * 商品详情
     *
     * @param id
     * @return
     */
    @RequestMapping("/product")
    public String product(Integer id, Model model, HttpSession session) {

        //查询商品
        EasybuyProduct product = productMapper.selectById(id);

        model.addAttribute("product", product);

        model.addAllAttributes(classify(session));


        return "product";
    }

    /**
     * 查询分类
     *
     * @return
     */
    public Map classify(HttpSession session) {
        //获取session
        EasybuyUser userSession = (EasybuyUser) session.getAttribute("userSession");

        List<EasybuyProductCategory> list = categoryMapper.selectList(new QueryWrapper<EasybuyProductCategory>().eq("type", 1));
        List<EasybuyProductCategory> list2 = categoryMapper.selectList(new QueryWrapper<EasybuyProductCategory>().inSql("parentId", "select id from easybuy_product_category where type=1"));
        List<EasybuyProductCategory> list3 = categoryMapper.selectList(new QueryWrapper<EasybuyProductCategory>().inSql("parentId", "select id from easybuy_product_category where type=2"));
        List<EasybuyNews> easybuyNews = newsMapper.selectList(new QueryWrapper<EasybuyNews>().last("limit 0,5"));

        List<ShoppingCar> order = carMapper.selectList(new QueryWrapper<ShoppingCar>().eq("userId", userSession == null ? 0 : userSession.getId()).eq("isDelete", 0));    //查询购物车

        //创建map集合
        Map<String, Object> map = new HashMap<>();

        map.put("list", list);//分类1
        map.put("list2", list2);//分类2
        map.put("list3", list3);//分类3
        map.put("easybuyNews", easybuyNews);  //新闻
        map.put("order", order);  //购物车

        //保留2为小数点
        DecimalFormat df = new DecimalFormat(".00");

        //总价格
        double sumPrice = 0;

        //循环订单
        for (ShoppingCar news : order) {

            //累加
            sumPrice += news.getSumPrice();
        }

        //保留2位小数点
        sumPrice = Double.parseDouble(df.format(sumPrice));

        //赋值总价格
        map.put("sumPrice", sumPrice);

        //赋值购物车数量
        session.setAttribute("order", order);

        //赋值总价格
        session.setAttribute("sumPrice", sumPrice);


        return map;
    }

    /**
     * 结算购物车方法
     *
     * @return
     */
    @RequestMapping("/settlement")
    public String settlement(HttpSession session, Model model) {

        //获取session
        EasybuyUser user = (EasybuyUser) session.getAttribute("userSession");

        //查询购物车是否为空
        List<ShoppingCar> cars = carMapper.selectList(new QueryWrapper<ShoppingCar>().eq("userId", user.getId()).eq("isDelete", 0));

        model.addAllAttributes(classify(session));
        model.addAttribute("cars",cars);


        return "BuyCar";

    }


    /**
     * 修改数量
     *
     * @param id     商品id
     * @param number 数量
     * @return
     */
    @RequestMapping("/updateNumber")
    @ResponseBody
    public Map<String, Object> updateNumber(Integer id, Integer number, String type, HttpSession session) {


        //获取session
        EasybuyUser user = (EasybuyUser) session.getAttribute("userSession");

        //创建map集合
        Map<String, Object> map = new HashMap<>();

        //查询购物车
        List<ShoppingCar> cars = carMapper.selectList(new QueryWrapper<ShoppingCar>().eq("id", id).eq("isDelete", 0));

        //赋值到购物车对象
        ShoppingCar car = cars.get(0);

        //商品对象
        EasybuyProduct product = productMapper.selectById(car.getProductId());

        System.out.println("购物车对象：" + car);

        //判断是加时
        if (type.equals("+")) {

            //计算加了多少
            Integer productNumber = number - car.getNumber();

            System.out.println("增加了：" + productNumber);

            //判断增加的数量小于大于库存数量
            if (productNumber <= product.getStock()) {

                //创建商品类对象
                EasybuyProduct easybuy = new EasybuyProduct();
                easybuy.setId(car.getProductId());//赋值商品类id
                easybuy.setStock(product.getStock() - productNumber);

                //修改库存
                int row = productMapper.updateById(easybuy);

                //判断修改库存成功
                if (row > 0) {

                    //创建购物车类对象
                    ShoppingCar shoppingCar = new ShoppingCar();
                    shoppingCar.setId(id);  //赋值id
                    shoppingCar.setNumber(car.getNumber() + productNumber);
                    shoppingCar.setSumPrice((double) shoppingCar.getNumber() * car.getPrice());
                    //修改购物车类
                    int rows = carMapper.updateById(shoppingCar);

                    //判断修改购物车成功
                    if (rows > 0) {

                        //查询购物车
                        List<ShoppingCar> order = carMapper.selectList(new QueryWrapper<ShoppingCar>().eq("userId", user.getId()).eq("isDelete", 0));

                        map.put("status", 1);
                        map.put("message", "修改成功！");
                        map.put("order", order);

                    } else {
                        map.put("status", 0);
                        map.put("message", "修改购物车失败，服务器内部错误！");
                    }

                } else {

                    map.put("status", 0);
                    map.put("message", "修改库存失败，服务器内部错误！");

                }


            } else {

                map.put("status", 0);
                map.put("message", "库存数量不足！");

            }

            //减时
        } else {

            //计算加了多少
            Integer productNumber = car.getNumber() - number;

            System.out.println("减少了：" + productNumber);

            //创建商品类对象
            EasybuyProduct easybuy = new EasybuyProduct();
            easybuy.setId(car.getProductId());//赋值商品类id
            easybuy.setStock(product.getStock() + productNumber);

            //修改库存
            int row = productMapper.updateById(easybuy);

            //判断修改库存成功
            if (row > 0) {

                //创建购物车类对象
                ShoppingCar shoppingCar = new ShoppingCar();
                shoppingCar.setId(id);  //赋值id
                shoppingCar.setNumber(car.getNumber() - productNumber);
                shoppingCar.setSumPrice((double) shoppingCar.getNumber() * car.getPrice());

                //修改购物车类
                int rows = carMapper.updateById(shoppingCar);

                //判断修改购物车成功
                if (rows > 0) {

                    //查询购物车
                    List<ShoppingCar> order = carMapper.selectList(new QueryWrapper<ShoppingCar>().eq("userId", user.getId()).eq("isDelete", 0));

                    map.put("status", 1);
                    map.put("message", "修改成功！");
                    map.put("order", order);
                } else {
                    map.put("status", 0);
                    map.put("message", "修改购物车失败，服务器内部错误！");
                }

            } else {

                map.put("status", 0);
                map.put("message", "修改库存失败，服务器内部错误！");

            }

        }

        return map;
    }

    /**
     * 删除购物车方法
     *
     * @param id
     * @return
     */
    @RequestMapping("/deleteByCar")
    @ResponseBody
    public Map<String, Object> deleteByCar(Integer id, HttpSession session) {

        //创建map集合
        Map<String, Object> map = new HashMap<>();

        //获取session
        EasybuyUser user = (EasybuyUser) session.getAttribute("userSession");

        //购物车类对象
        ShoppingCar car = new ShoppingCar();
        car.setId(id);
        car.setIsDelete(1);

        //修改购物车状态
        int row = carMapper.updateById(car);

        //判断删除成功
        if (row > 0) {

            //查询当前删除的商品
            ShoppingCar car1 = carMapper.selectById(id);

            //查询商品
            EasybuyProduct product1 = productMapper.selectById(car1.getProductId());

            //商品类
            EasybuyProduct product = new EasybuyProduct();
            product.setId(car1.getProductId());
            product.setStock(product1.getStock() + car1.getNumber());

            //修改库存
            int update = productMapper.updateById(product);

            //判断修改成功
            if (update > 0) {

                //查询购物车
                List<ShoppingCar> order = carMapper.selectList(new QueryWrapper<ShoppingCar>().eq("userId", user.getId()).eq("isDelete", 0));

                map.put("status", 1);
                map.put("message", "删除成功！");
                map.put("order", order);

            } else {

                map.put("status", 0);
                map.put("message", "修改库存失败！");

            }


        } else {
            map.put("status", 0);
            map.put("message", "删除失败！");
        }

        return map;
    }

    /**
     * 结算第二步
     *
     * @param session
     * @return
     */
    @RequestMapping("/buyCarTwo")
    public String buyCarTwo(HttpSession session, Model model) {

        //获取session
        EasybuyUser user = (EasybuyUser) session.getAttribute("userSession");

        //查询购物车
        List<ShoppingCar> order = carMapper.selectList(new QueryWrapper<ShoppingCar>().eq("userId", user.getId()).eq("isDelete", 0));

        //查询地址
        List<EasybuyUserAddress> addressList = addressMapper.selectList(new QueryWrapper<EasybuyUserAddress>().eq("userId", user.getId()));

        //总金额
        double sumPrice = 0;

        for (ShoppingCar o : order) {

            sumPrice += o.getSumPrice();

        }

        model.addAttribute("order", order);
        model.addAttribute("addressList", addressList);
        model.addAttribute("sumPrice", sumPrice);
        model.addAllAttributes(classify(session));

        return "BuyCar_Two";
    }


}

